package com.atguigu.lease.web.admin.controller.login;


import com.atguigu.lease.common.result.Result;
import com.atguigu.lease.common.utils.JwtUtils;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Tag(name = "后台管理系统登录管理")
@RestController
@RequestMapping("/admin")
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private SystemUserService systemUserService;

    @Operation(summary = "获取图形验证码")
    @GetMapping("login/captcha")
    public Result<CaptchaVo> getCaptcha() {
        CaptchaVo vo = loginService.getCpatcha();
        return Result.ok(vo);
    }

    @Operation(summary = "登录")
    @PostMapping("login")
    public Result<String> login(@RequestBody LoginVo loginVo) {
        String result = loginService.login(loginVo);
        return Result.ok(result);
    }

    @Operation(summary = "获取登陆用户个人信息")
    @GetMapping("info")
    public Result<SystemUserInfoVo> info(@RequestHeader("Access_token") String token) {
        Claims loadData = JwtUtils.parseToken(token);
        //Claims 本质上 = Map<String, Object> 当你从 Map 里取值时，它不知道你要的是什么类型：
        //JWT的自动优化机制 如果你存的值比较小,那么会自动转换成Integer类型 也就是小范围的
        Integer userId = loadData.get("userId", Integer.class);
        SystemUser user = systemUserService.getById(userId);
        SystemUserInfoVo vo = new SystemUserInfoVo();
        vo.setName(user.getName());
        vo.setAvatarUrl(user.getAvatarUrl());
        return Result.ok(vo);
    }
}